/*
* @Author: song
* @Description:脚本流水线
* @Date: 2024年04月18日 星期四 14:04:08
* @Modify:
*/

using System;
using System.Collections.Generic;

namespace SCore.Function.ScriptPipeline
{
    public class ScriptPipeline
    {
        private Action _complete;
        private Queue<ScrpitPipelineAction> _actions = new Queue<ScrpitPipelineAction>();
        private List<ScrpitPipelineAction> _running = new List<ScrpitPipelineAction>();

        public ScriptPipeline Add(ScrpitPipelineAction pipelineAction)
        {
            pipelineAction.Config(this);
            _actions.Enqueue(pipelineAction);
            return this;
        }

        public void Complete(Action action)
        {
            _complete = action;
        }

        public ScriptPipeline Execute()
        {
            _running.Add(_actions.Dequeue());
            return this;
        }

        public void Next()
        {
            if (_actions.Count != 0)
            {
                Execute();
            }
        }

        public void End(ScrpitPipelineAction sPipelineAction)
        {
            if (_running.Contains(sPipelineAction))
            {
                _running.Remove(sPipelineAction);
                if (_running.Count == 0)
                {
                    _complete?.Invoke();
                }
            }
            else
            {
                $"{sPipelineAction.GetType().Name} is not in running".Warn();
            }
        }

        public void SUpdate(float dt)
        {
            for (int index = _running.Count - 1; index >= 0; index--)
            {
                _running[index].SUpdate(dt);
            }
        }
    }
}